-- 發起電子郵件验证


local httparg    = require("shared.api.httparg")
local response   = require("shared.api.response")
local config     = require("config")
local tag        = httparg.tag()
local assertion  = httparg.assertion

local cjson = require "cjson.safe"
cjson.encode_max_depth(32)
cjson.decode_max_depth(32)





local ARGS = {
  tag.body('json', 'required'),

  account       = tag.json.account       ('string', assertion.non_empty_string()),
  email         = tag.json.email         ('string', assertion.non_empty_string()),
  verify_code   = tag.json.verify_code   ('string', 'required', assertion.non_empty_string()),

}

do
  local config  = require("config")
  local def         = require "shared.api.def"
  local GAAS_SHARED_REDIS  = config.GAAS_SHARED_REDIS
  local REDIS_SETTINGS     = config.REDIS_SETTINGS
  local redis = require("shared.api.redis-adapter").new(GAAS_SHARED_REDIS) -- , response.redis_error_reply



  --datagate 更新邮箱验证状态
  local httpclient = require "shared.http.client"
  local location = config.ENV.DATAGATE_SERVICE .. "/account"
  local headers  = ngx.req.get_headers()
  local query    = nil

  do
      -- add X-Forwarded-For header
      headers['X-Forwarded-For'] = ngx.var.proxy_add_x_forwarded_for
  end


  --移除方法设定
  local rmvLowKey="x-http-method-override"
  --移除gzip设定
  local rmvKey2="accept-encoding"
  for k,v in pairs(headers) do
      local low=string.lower(k)
      if low==rmvLowKey  or low==rmvKey2   then
          headers[k]=nil
      end
  end

  local method   = "CONFIRM"
  local bodyMap  = {}
  bodyMap.account=ARGS.account
  bodyMap.content={
      email_verified=true
  }
  local requestData = cjson.encode(bodyMap)



  local key=string.format("%s/verify_code/account:%s/email:%s","ocpgateway",ARGS.account,ARGS.email)
  ngx.log(ngx.ERR, key)
  local res, err = redis:get(key)
  if not res then
      ngx.say("failed to get verify_code: ", err)
      return
  end
  ngx.log(ngx.ERR, res)
  if res == ngx.null then
      response.failure(def.ERROR_CODE.VERIFY_CODE_EXPIRE, 'VERIFY_CODE_EXPIRE')
      return
  end
  if res~=ARGS.verify_code then
  response.failure(def.ERROR_CODE.VERIFY_CODE_ERROR, 'VERIFY_CODE_ERROR')
  end

   -- 更新邮箱验证状态

  local resp, err = httpclient.new()
                              :uri(location)
                              :headers(headers)
                              :query(query)
                              :body(requestData)
                              :send(method, 2000, nil)

  if err or (not resp) then
      ngx.status = 500
      ngx.say(err)
      ngx.exit(ngx.OK)
  end

end

  local RESULT

    RESULT = {}


  response.success(RESULT)